package com.wzcl.app.config.oauth.model;

import com.wzcl.app.dao.model.AppRole;
import com.wzcl.app.dao.model.AppUser;
import com.wzcl.app.model.common.WZCL;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class UserDetailsImpl implements UserDetails, CredentialsContainer {
    private Integer id;
    private String phone;
    private String password;
    private String nickName;
    private String realName;
    private Integer userState;
    private Integer state;
    private String type;
    private Collection<GrantedAuthority> grantedAuthorities;

    public UserDetailsImpl(AppUser user) {
        BeanUtils.copyProperties(user,this);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (user.getRoleList()!=null && user.getRoleList().size()>0){
            for (AppRole appRole : user.getRoleList()) {
                grantedAuthorities.add(new SimpleGrantedAuthority(appRole.getName()));
            }
        }
        this.setGrantedAuthorities(grantedAuthorities);
    }

    @Override
    public void eraseCredentials() {
        this.password = null;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.phone;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return WZCL.USER_STATE.EFFECTIVE.equals(userState);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return WZCL.STATE.NOT_DELETE.equals(state);
    }


}
